var $workOrderTableList = $('#workOrderList');
//防止表头与表格不对齐
$(window).resize(function () {
    $workOrderTableList.bootstrapTable('resetView');
});

$(function () {
    selectTime("all");
    searchWorkOrderList();
    // ajaxForm()
});

function searchWorkOrderList(){
    $workOrderTableList.bootstrapTable('destroy');
    $workOrderTableList.bootstrapTable({
        classes: 'table table-hover table-bordered table-striped ',
        url: '/workOrder/workOrderList',                            // 请求地址
        method: 'post',                                         // 请求方式
        contentType: "application/x-www-form-urlencoded",       // 请求内容类型
        dataType: "json",                                       // 数据类型
        striped: true,                                          // 是否显示行间隔色
        sortable: true,                                         // 是否启用排序
        sortOrder: "desc",                                      // 排序方式
        sortName: 'createTm',                                   // 排序字段
        cache: false,                                           // 是否使用缓存
        showColumns: false,                                     // 显示隐藏列
        showRefresh: false,                                     // 显示刷新按钮
        showToggle: false,                                      // 切换显示样式
        showFooter: false,                                      // 显示Table脚部
        pagination: true,                                       // 是否显示分页
        showPaginationSwitch: false,                            // 是否显示分页按钮
        clickToSelect: true,                                    // 是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,                                 // 最少要显示的列数
        undefinedText: '',                                      // cell没有值时显示
        sidePagination: "server",                               // 分页方式：client客户端分页，server服务端分页
        uniqueId: 'workOrderId',
        idField: 'workOrderId',
        pageSize: globalPageSize,                                            // 每页的记录行数
        pageNumber: 1,                                          // 初始化加载第1页，默认第1页
        pageList: globalPageList,                            // 可供选择的每页的行数
        queryParams: queryParams,                               // 查询参数
        columns: [
            {title: '工单Id', field: 'workOrderId', visible: false},
            {title: '工单号', field: 'workOrderNumber', align: 'left', valign: 'middle', width: '', formatter: contactTableList.workOrderNumber},
            {title: '工单标题', field: 'workOrderTitle', align: 'left', valign: 'middle', width: '', formatter: contactTableList.workOrderTitle},
            {title: '类型', field: 'typeStr', align: 'left', valign: 'middle', width: ''},
            {title: '状态', field: 'statusStr', align: 'left', valign: 'middle', width: ''},
            {title: '时间', field: 'createTm', align: 'left', valign: 'middle', width: ''},
            {title: '提交人', field: 'userName', align: 'left', valign: 'middle', width: '', formatter: contactTableList.createPeopleId},
            {title: '操作', field: '', align: 'right', valign: 'middle', width: '', formatter: contactTableList.operation},
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function (data) {
            // $("[data-toggle='tooltip']").tooltip();
            $(document).on('mouseenter', '.contact-header', function () {
                var $this = $(this);
                var scrollTop = $(document).scrollTop();
                var tLeft = $(this).offset().left;
                var tTop = $(this).offset().top;

                $this.removeClass('hide-action');
                $this.css('z-index', '10').find('.action').css({
                    position: 'fixed',
                    left: tLeft + 38,
                    top: tTop - scrollTop - 29,
                });
                $(document).scroll(debounce(function () {
                    $this.addClass('hide-action');
                }, 200, true));
            }).on('mouseleave', '.contact-header', function () {
                $(this).css('z-index', '1')
            });
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

function queryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式

    params.dateType= $("#dateType").val();
    params.workOrderNumber = $("#workOrderNumber").val();
    params.workOrderTitle = $("#workOrderTitle").val();
    params.userName = $("#userName").val();
    // params.bs = "0";

    //产品列表搜索条件
    return params;
}

// // 全部 本周 本月
function selectTime(time) {
    $('.selector-box dd a').removeClass('active');
    $('.selector-box dl dd:first-of-type a').addClass('active');
    if (time == 'all') {//全部
        $('.all').addClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.me').removeClass('active-second');
        $("#dateType").val("all");
    }
    if (time == 'month') {//本月
        $('.month').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.me').removeClass('active-second');
        $("#dateType").val("thisMonth");
    }
    if (time == 'week') {//本周
        $('.week').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.me').removeClass('active-second');
        $("#dateType").val("thisWeek");
    }
    if (time == 'me') {//本周
        $('.me').addClass('active-second');
        $('.week').removeClass('active-second');
        $('.all').removeClass('active-second');
        $('.month').removeClass('active-second');
        $("#dateType").val("me");
    }
    $workOrderTableList.bootstrapTable('refreshOptions', {pageNumber: 1});
}

/**
 * 功能：联系人列表自定义内容
 * */
var contactTableList = {
    //工单号
    workOrderNumber:function (value, row, index, field) {
        let html = '';
        if (value) {
            html = '<div>' + value + '</div>';
        }
        return html;
    },
    //工单标题
    workOrderTitle: function (value, row, index, field) {
        let html = '';
        if (value) {
            if(row.detail==1 || row.detail=='null'){
                html = '<div  style="color: #ff0000;">' + value + '</div>';

            }else{
                html = '<div>' + value + '</div>';
            }

        }
        return html;
    },
    /*//时间
    createTm: function (value, row, index, field) {
        var html;
        if (value) {
            var followTime = new Date(value).Format("yyyy-MM-dd HH:mm:ss");
            html = '<div class="time">' + followTime + '</div>';
        }
        return html;
    },*/
    //提交人
    createPeopleId: function (value, row, index, field) {
        let html = '';
        if (value) {
            html = '<div>' + value + '</div>';
        }
        return html;
    },

    operation: function (value, row, index, field) {
        //userName
        //\'' + row.productActivityId + '\', \'' + newShelfStatus + '\'
        let html=''
        if(row.detail==1 || row.detail=='null'){
            html += '<button type="button" class="btn btn-default" disabled onclick="workOrderReply(\'' + row.workOrderId + '\',\''+row.userName+'\')"><i class="mdi mdi-eye"></i>详情</button>';


        }else{
            html += '<button type="button" class="btn btn-default" onclick="workOrderReply(\'' + row.workOrderId + '\',\''+row.userName+'\')"><i class="mdi mdi-eye"></i>详情</button>';

        }
        // html += '<button class="btn btn-default" id="detail" onclick="startRdit(\'' + row.workOrderId + '\',\''+row.statusStr+'\')">设置状态</button>';
        return html;
    },
}


/**
 * 自定义操作列事件
 */
// window.operateEvents = {
//     //设置状态事件
//     'click #detail': function (e, value, row, index) {
//     },
//
// };

/**
 * --列表序列号
 */
function indexFormat(value, row, index) {
    return index + 1;
}

/**
 * 新增工单
 */
function addWorkOrder() {
    parent.$(parent.document).data('multitabs').create({
        iframe: true,
        title: '新增工单',
        url: "/front/workOrderManager/addWorkOrder"
    }, true);
}

/**
 * 回复工单
 * @param content
 */


function promptInfo(content) {
    $.alert({
        title: '温馨提示',
        content: content,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary'
            }
        }
    });
}


/**
 * 回复工单
 * @param content
 */
var setworkOrderId='',listWork
function workOrderReply(workOrderId,userName) {
    //点击页面的回复弹出弹框
    // $('#addDemandAnalysisModel').modal('show');
    parent.$(parent.document).data('multitabs').create({
        iframe: true,
        title: '回复工单',
        url: "/front/workOrderManager/workOrderDetail?userName="+userName+"&workOrderId="+workOrderId
    }, true);
    // setworkOrderId=workOrderId
    // listWork={
    //     workOrderId:setworkOrderId
    // }
    // ajaxForm()
}

function startRdit(workOrderId,statusStr) {

    $.confirm({
        title: '设置状态',
        content: '<strong>\n' +
            '<p>确定要修改这一条状态吗?</p>\n' +
            '</strong>',
        icon: 'glyphicon glyphicon-question-sign',
        buttons: {
            ok: {
                text: '处理中',
                btnClass: 'btn-warning',
                action: function () {
                    ajaxStart(workOrderId,0)
                }
            },
            resolved: {
                text: '已解决',
                btnClass: 'btn-primary',
                action: function () {
                    ajaxStart(workOrderId,1)
                }
            },
            unresolved: {
                text: '未解决',
                btnClass: 'btn-danger',
                action: function () {
                    ajaxStart(workOrderId,2)
                }
            },
            cancel: {
                text: '取消',
                btnClass: 'btn-default',
                action: function () {

                }
            }
        }
    });

}


function ajaxStart(workOrderId,workStatus) {
    $.ajax({
        url: '/workOrder/updateWorkOrder',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify({
            workOrderId: workOrderId,
            workStatus:workStatus
        }),
        success: (function (data) {
            if (data.code == "000000") {

                $.alert({
                    title: '提示',
                    content: '修改成功！',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                $workOrderTableList.bootstrapTable('refresh');
                            }
                        }
                    }
                })


            } else {
                $.alert("操作失败");
            }
        }),
        error: (function () {
            $.alert("失败");
        })
    });
}

// function ajaxForm() {
//     workAjaxPost('/workOrder/workOrderReplyList',listWork,'application/x-www-form-urlencoded; charset=UTF-8').then((res)=>{
//         var htmlList=''
//         if(res.code=='000000'){
//             for(let i=0,len=res.data.length;i<len;i++){
//                 htmlList+=`<div class="follow-text">
//                         <h5>回复人：<span>${res.data[i].userName}</span>/<em>${res.data[i].createTm}</em></h5>
//                         <p>回复内容：${res.data[i].replyContent}</p>
//                     </div>`
//             }
//             $("#followList").html(htmlList)
//             // htmlList
//         }
//     })
// }
// //点击弹框的回复 // 回复工单 /workOrder/addWorkOrderReply
// function publish() {
//     $('.work-informat').bootstrapValidator({
//         fields: {
//             followContent: {
//                 validators: {
//                     notEmpty: {
//                         message: '回复信息不能为空'
//                     },
//                     stringLength: {
//                         max: 200,
//                         message: '回复信息长度必须200之间'
//                     }
//                 }
//             },
//
//
//         },
//     })
//     $(".work-informat").bootstrapValidator('validate');//提交验证
//     if (!$(".work-informat").data('bootstrapValidator').isValid()) {//获取验证结果，如果成功，执行下面代码
//
//         return;
//     }
//     var dataWork={
//         workOrderId:setworkOrderId,
//         replyContent:$("#followContent").val()
//     }
//
//     workAjaxPost('/workOrder/addWorkOrderReply',JSON.stringify(dataWork),'application/json;charset=utf-8').then((res)=>{
//         if(res.code=='000000'){
//
//             ajaxForm()
//         }
//     })
//     // $("#followContent").val('')
//     $("#addDemandAnalysisModel").find('form')[0].reset()
//     //
//     $(".t_h i").html($("#followContent").val().length)
//     if($(".work-informat").data('bootstrapValidator')!=undefined){
//         // $(".work-informat").data('bootstrapValidator').destroy();
//         $('.work-informat').data('bootstrapValidator', null);
//     }
//
// }
//
// $('#addDemandAnalysisModel').on('hidden.bs.modal', function (){
//
//     $(this).find('form')[0].reset()
//     $(".t_h i").html($("#followContent").val().length)
//     if($(".work-informat").data('bootstrapValidator')!=undefined){
//         $(".work-informat").data('bootstrapValidator').destroy();
//         $('.work-informat').data('bootstrapValidator', null);
//     }
//
// });
//
// //回复
// function changeReply() {
//     $(".t_h i").html($("#followContent").val().length)
// }


function workAjaxPost(url,data,contentType) {
    // contentType: "application/json;charset=utf-8",
    var promises=new Promise((resolve, reject)=>{
        $.ajax({
            type: 'post',
            url: url,
            data: data,
            contentType:contentType,
            dataType: 'json',
            async:false,
            success: function (res) {
                resolve(res)
                if(res.code!='000000'){
                    $.alert(res.message)
                }
            },
            error: function (res) {
                reject(res)
                $.alert(res.message)
            }
        });
    })

    promises.catch(function(error) {
        $.alert(error.message)
    });

    return promises

}


